package com.team1.system.libraryborrow.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.servlet.http.HttpServletResponse;

import com.team1.system.blockchain.controller.BlockController;
import com.team1.system.blockchain.domain.Block;
import com.team1.system.blockchain.domain.Transaction;
import com.team1.system.librarycredit.domain.LibraryCredit;
import com.team1.system.librarycredit.service.ILibraryCreditService;
import com.team1.system.stats.controller.StatsBorrowReturnController;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.team1.common.annotation.Log;
import com.team1.common.core.controller.BaseController;
import com.team1.common.core.domain.AjaxResult;
import com.team1.common.enums.BusinessType;
import com.team1.system.libraryborrow.domain.LibraryBorrow;
import com.team1.system.libraryborrow.service.ILibraryBorrowService;
import com.team1.common.utils.poi.ExcelUtil;
import com.team1.common.core.page.TableDataInfo;

/**
 * 借书信息管理Controller
 *
 * @author hyy
 * @date 2023-04-10
 */
@RestController
@RequestMapping("/librarysystem/libraryborrow")
public class LibraryBorrowController extends BaseController
{
    @Autowired
    private ILibraryBorrowService libraryBorrowService;
    @Autowired
    private ILibraryCreditService libraryCreditService;
    @Autowired
    private StatsBorrowReturnController statsBorrowReturnController;
    @Autowired
    private BlockController blockController;

    /**
     * 查询借书信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:list')")
    @GetMapping("/list")
    public TableDataInfo list(LibraryBorrow libraryBorrow)
    {
        startPage();
        List<LibraryBorrow> list = libraryBorrowService.selectLibraryBorrowList(libraryBorrow);
        return getDataTable(list);
    }

    /**
     * 导出借书信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:export')")
    @Log(title = "借书信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LibraryBorrow libraryBorrow)
    {
        List<LibraryBorrow> list = libraryBorrowService.selectLibraryBorrowList(libraryBorrow);
        ExcelUtil<LibraryBorrow> util = new ExcelUtil<LibraryBorrow>(LibraryBorrow.class);
        util.exportExcel(response, list, "借书信息管理数据");
    }

    /**
     * 获取借书信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:query')")
    @GetMapping(value = "/{borrowId}")
    public AjaxResult getInfo(@PathVariable("borrowId") String borrowId)
    {
        return success(libraryBorrowService.selectLibraryBorrowByBorrowId(borrowId));
    }

    /**
     * 新增借书信息管理
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:add')")
    @Log(title = "借书信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LibraryBorrow libraryBorrow)
    {
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddhhmmss");
        int random=(int)(Math.random()*900)+100;
        String id=format.format(date)+random;
        libraryBorrow.setBorrowId("borrow"+id);
        libraryBorrow.setUserId(getUserId());
        return toAjax(libraryBorrowService.insertLibraryBorrow(libraryBorrow));
    }

    /**
     * 修改借书信息管理
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:return')")
    @Log(title = "借书信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/return")
    public AjaxResult returnBook(@RequestBody LibraryBorrow libraryBorrow)
    {
        if (libraryBorrow.getReturnIs().equals("1")){
            return error("该书已还，请勿重复操作");
        }
        if (libraryBorrow.getBorrowAdminid()==null){
            return error("操作失败");
        }
        libraryBorrow.setReturnIs("1");
        return toAjax(libraryBorrowService.updateLibraryBorrow(libraryBorrow));
    }

    /**
     * 修改借书信息管理
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:edit')")
    @Log(title = "借书信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LibraryBorrow libraryBorrow)
    {
        if (libraryBorrow.getBorrowAdminid()!=null){
            return error("已通过，请勿重复操作");
        }
        Date date=new Date();
        libraryBorrow.setBorrowAdminid(getUserId());
        libraryBorrow.setBorrowTime(date);
        return toAjax(libraryBorrowService.updateLibraryBorrow(libraryBorrow));
    }

    /**
     * 修改借书信息管理
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:edit')")
    @Log(title = "借书信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit2")
    public AjaxResult edit2(@RequestBody LibraryBorrow libraryBorrow)
    {
        if (libraryBorrow.getReturnIs().equals("0")){
            return error("该书未归还");
        }
        if (libraryBorrow.getReturnAdminid()!=null){
            return error("已通过，请勿重复操作");
        }
        Date date=new Date();
        libraryBorrow.setReturnAdminid(getUserId());
        libraryBorrow.setReturnTime(date);
        return toAjax(libraryBorrowService.updateLibraryBorrow(libraryBorrow));
    }

    @PreAuthorize("@ss.hasPermi('librarysystem:librarycredit:add')")
    @Log(title = "信用度信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/creditadd")
    public void creditAdd(@RequestBody String borrowId){
        LibraryBorrow libraryBorrow=libraryBorrowService.selectLibraryBorrowByBorrowId(borrowId);
        //新增信用度信息
        LibraryCredit libraryCredit=new LibraryCredit();
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddhhmmss");
        int random=(int)(Math.random()*900)+100;
        String id=format.format(date)+random;
        libraryCredit.setCreditId("credit"+id);
        libraryCredit.setUserId(libraryBorrow.getUserId());
        libraryCredit.setBookId(libraryBorrow.getBookId());
        libraryCredit.setBorrowId(libraryBorrow.getBorrowId());
        libraryCredit.setCreditTobc("0");
        double borrowTime=statsBorrowReturnController.BorrowIdTime(libraryBorrow.getBorrowId());
        String offset="";
        if (borrowTime>168){
            offset='-'+Double.toString((int)(borrowTime-72)/24+1);
        } else {
            offset=Double.toString((int)borrowTime/24);
        }
        libraryCredit.setCreditOffset(offset);
        libraryCreditService.insertLibraryCredit(libraryCredit);
    }

    /**
     * 上链借书信息管理
     */
    @PreAuthorize("@ss.hasPermi('librarysystem:libraryborrow:block')")
    @Log(title = "借书信息管理", businessType = BusinessType.DELETE)
	@PostMapping("/block")
    public AjaxResult upBlock(@RequestBody String[] borrowIds)
    {
        List<Transaction> transactions = new CopyOnWriteArrayList<Transaction>();
        int trsId=1;
        for (String str:borrowIds){
            LibraryBorrow borrow=libraryBorrowService.selectLibraryBorrowByBorrowId(str);

            if (borrow.getBorrowTobc().equals("1")){
                return error("存在已上链信息");
            }

            Transaction transaction=new Transaction();
            transaction.setId(trsId);
            trsId=trsId+1;
            transaction.setBorrowId(borrow.getBorrowId());
            transaction.setUserId(borrow.getUserId());
            transaction.setBookId(borrow.getBookId());
            transaction.setBorrowAdminid(borrow.getBorrowAdminid());
            transaction.setBorrowTime(borrow.getBorrowTime());
            transaction.setReturnAdminid(borrow.getReturnAdminid());
            transaction.setReturnTime(borrow.getReturnTime());
            LibraryCredit credit=new LibraryCredit();
            List<LibraryCredit> creditList=libraryCreditService.selectLibraryCreditList(credit);
            for (LibraryCredit l:creditList){
                if (l.getBorrowId().equals(borrow.getBorrowId())){
                    credit=l;
                }
            }
            transaction.setCreditId(credit.getCreditId());
            transaction.setCreditOffset(credit.getCreditOffset());
            transactions.add(transaction);

            borrow.setBorrowTobc("1");
            credit.setCreditTobc("1");
            libraryBorrowService.updateLibraryBorrow(borrow);
            libraryCreditService.updateLibraryCredit(credit);
        }
        return success(blockController.upBlock(transactions));
    }
}
